package com.fc.happyteam.utils.tree;

import java.util.*;

public class MultipleTreeUtil {
    public static List<Node> buildTreeNode(List dataList, boolean sort) {
        // 节点列表（散列表，用于临时存储节点对象）
        HashMap nodeList = new HashMap();
        // 根节点
        List<Node> roots = new ArrayList<>();
        // 根据结果集构造节点列表（存入散列表）
        for (Iterator it = dataList.iterator(); it.hasNext(); ) {
            Map dataRecord = (Map) it.next();
            Node node = new Node();
            node.id = (Integer) dataRecord.get("id");
            node.value = (String) dataRecord.get("name");
            node.label = (String) dataRecord.get("label");
            node.parentId = (Integer) dataRecord.get("parentId");
            nodeList.put(node.id, node);
        }
        // 构造无序的多叉树
        Set entrySet = nodeList.entrySet();
        for (Iterator it = entrySet.iterator(); it.hasNext(); ) {
            Node node = (Node) ((Map.Entry) it.next()).getValue();
            if (node.parentId == null || node.parentId.equals("")) {
                //root = node;
                roots.add(node);
            } else {
                ((Node) nodeList.get(node.parentId)).addChild(node);
            }
        }

        if (roots.size() > 0) {
            for (Node root : roots) {
                if (sort) {
                    // 对多叉树进行横向排序
                    root.sortChildren();
                }
            }
        }
        return roots;
    }
}
